<template>
  <div class="dropdown">
    <button class="dropdown-toggle" @click="toggleDropdown">
      {{ selectedLabel? selectedLabel : 'CIBN播控终端统计' }}
      <span class="dropdown-icon"></span>
    </button>
    <ul v-if="isOpen" class="dropdown-menu">
      <li v-for="(option, index) in options" :key="index" @click="selectOption(option)">
        {{ option }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue';

// 接收父组件传递的选中值和选项
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  options: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['selectValue']);

const selectedLabel = ref(props.modelValue);
const isOpen = ref(false);

// 切换下拉菜单显示与隐藏
const toggleDropdown = () => {
  isOpen.value = !isOpen.value;
};

// 选择菜单项
const selectOption = (option) => {
  selectedLabel.value = option;
  emit('selectValue', option); // 将选中的值传递给父组件
  isOpen.value = false; // 选择后关闭菜单
};

// 监听父组件传递的选中值，更新选中项
watch(() => props.modelValue, (newValue) => {
  selectedLabel.value = newValue;
});
</script>

<style scoped>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-toggle {
  width: 155px;
  padding: 5px;
  font-size: 14px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.dropdown-icon {
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 6px solid #333;
  position: absolute;
  right: 20px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  list-style: none;
  padding: 0;
  margin: 0;
  font-size: 14px;;
  color: #000;
  text-align: center;
}

.dropdown-menu li {
  padding: 8px 12px;
  cursor: pointer;
}

.dropdown-menu li:hover {
  background-color: #f5f5f5;
}
</style>
